<template>
  <el-card class="box-card" v-loading="loading">
    <template #header>
      <div class="card-header">
        <span>生产工单数据明细</span>
      </div>
    </template>

    <div v-if="!loading && (overviewData && detailsData)">
      <!-- 工单概览组件 -->
      <WorkOrderOverview :data="overviewData" />

      <ReportingDetails v-if="viewMode === 'reporting'" :data="detailsData" />

      <QualityMonitoringData v-if="viewMode === 'quality'" :data="qualityData" />

    </div>
    <el-empty v-else-if="!loading" description="未查询到相关数据" />
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { ElCard, ElEmpty } from 'element-plus';

import WorkOrderOverview from './WorkOrderOverview.vue';
import ReportingDetails from './ReportingDetails.vue';
import QualityMonitoringData from './QualityMonitoringData.vue';

import { OrderApi,OrderVO } from '@/api/order/index'          // 新增：订单 API
import { ProductionWorkOrderApi,ProductionWorkOrderVO } from '@/api/productionworkorder/index'  // 新增：生产工单 API
import { QualityMonitoringDataApi, QualityMonitoringDataVO } from '@/api/qualitymonitoringdata';

// 定义 props，接收外部传入的销售订单号
const props = defineProps({
  salesOrderNumber: {
    type: String,
    required: true,
  },
  viewMode: {
    type: String,
    default: 'reporting',
  }
});

const loading = ref(true);
const overviewData = ref<OrderVO | null>(null);
const detailsData = ref<ProductionWorkOrderVO[]>([]);
const qualityData = ref<QualityMonitoringDataVO[]>([]);

const fetchOrderDetails = async (orderNumber: string) => {
  loading.value = true;
  try {
    // 1. 通过订单 API 获取概览数据（假设 orderNumber 是订单 ID，需根据实际接口调整参数）
    const orderDetail = await OrderApi.getOrderByCode(orderNumber);  // 注意：需确认订单 ID 是否为数字类型
    overviewData.value = orderDetail

    // 2. 通过生产工单 API 获取明细数据（传递销售订单号作为筛选条件）
    console.log("==========",props.viewMode)
    if(props.viewMode === 'reporting'){
      const workOrderList = await ProductionWorkOrderApi.getList({ 
        salesOrderNo: orderNumber 
      });
      detailsData.value = workOrderList;  // 假设返回的列表直接匹配明细组件需求
    }
    if(props.viewMode === 'quality'){
      const qualityList = await QualityMonitoringDataApi.getBySaleOrderCode( orderNumber);
      qualityData.value = qualityList;  // 假设返回的列表直接匹配明细组件需求
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时首次加载数据
onMounted(() => {
  fetchOrderDetails(props.salesOrderNumber);
});

// 监听 salesOrderNumber 属性的变化，如果变化则重新加载数据
watch(() => props.salesOrderNumber, (newVal) => {
  if (newVal) {
    fetchOrderDetails(newVal);
  }
});

</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}
</style>